package com.xuanwei.admin.controller;

import com.github.tobato.fastdfs.exception.FdfsUnsupportImageTypeException;
import com.xuanwei.core.response.ResultVO;
import com.xuanwei.core.exception.XwException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/4/23 15:34
 **/
@RestControllerAdvice
@Slf4j
public class ExceptionController {

    /**
     * 请求方式错误
     *
     * @param request request
     * @return 响应
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultVO notSupportedException(HttpServletRequest request) {
        return ResultVO.failResult(request.getMethod() + "请求方式错误");
    }

    /**
     * 登陆异常
     *
     * @return 响应
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    public ResultVO badCredentialsException() {
        return ResultVO.failResult("用户名或密码错误");
    }


    /**
     * fastDfs上传图片异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = FdfsUnsupportImageTypeException.class)
    public ResultVO fdfsUnsupportImageTypeException(Exception e) {
        return ResultVO.failResult(e.getMessage());
    }

    /**
     * 总异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = Exception.class)
    public ResultVO exception(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return ResultVO.failResult("系统异常");
    }


    /**
     * 自定义异常
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = XwException.class)
    public ResultVO xwException(Exception e) {
        return ResultVO.failResult(e.getMessage());
    }

    /**
     * 参数校验
     *
     * @param e e
     * @return 响应
     */
    @ExceptionHandler(value = BindException.class)
    public ResultVO bindException(BindException e) {
        List<ObjectError> allErrors = e.getAllErrors();
        String defaultMessage = allErrors.get(0).getDefaultMessage();
        return ResultVO.failResult(defaultMessage);
    }

    /**
     * 方法上参数校验
     *
     * @param e 异常
     * @return 响应
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultVO bindException(ConstraintViolationException e) {
        return ResultVO.failResult(e.getMessage());
    }

    /**
     * 格式化日期参数
     *
     * @param binder
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {

        binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isNotBlank(text)) {
                    setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }

            }
        });
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isNotBlank(text)) {
                    setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            }
        });
        binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isNotBlank(text)) {
                    setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));

                }
            }
        });
    }
}
